第一行代码Android学习:第十部分主要涉及到Android多线程编程和Service的用法
1.DYHDM_09_00AndroidThreadServiceTest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dyhdm_09_00androidthreadtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.dyhdm_09_00androidthreadtest.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
<service android:name=".MyService" >
service>
<service android:name=".MyIntentService" >
service>
application>
manifest>
/*
* @Title: DownloadTask.java
* @Description: TODO
* @author: 张志安
* @date: 2016-8-18 下午4:06:45
*
*/
package com.example.dyhdm_09_00androidthreadtest;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
/**
* TODO AsyncTask
*
* @author 张志安
* @date: 2016-8-18 下午4:06:45
*/
public class DownloadTask extends AsyncTask<Void, Integer, Boolean> {
/**
* 重载方法 在后台任务开始执行前调用 执行准备工作
*/
@Override
protected void onPreExecute() {
super.onPostExecute(null);
//显示进度条对话框
}
/**
* 重载方法 这个方法中所有的代码都会在子线程中执行 执行耗时操作
*/
@Override
protected Boolean doInBackground(Void... params) {
publishProgress(0);
return null;
}
/**
* 重载方法 在调用publishProgress()后执行 进行UI操作
*/
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
/**
* 重载方法 后台任务执行完毕并通过return语句进行返回时调用 执行任务收尾工作
*/
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
}
}
package com.example.dyhdm_09_00androidthreadtest;
import com.example.dyhdm_09_00androidthreadtest.MyService.DownloadBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button bt1;
private TextView tv1;
private Button bt2;
private Button bt3;
private Button bt4;
private Button bt5;
private Button bt6;
private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadBinder = (MyService.DownloadBinder) service;
downloadBinder.startDown();
downloadBinder.getProgress();
}
};
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
tv1.setText("123");
break;
default:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.bt1);
tv1 = (TextView) findViewById(R.id.tv1);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
}).start();
}
});
// 启动异步任务
// new DownloadTask().execute();
bt2 = (Button) findViewById(R.id.bt2);
bt3 = (Button) findViewById(R.id.bt3);
bt2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 开始服务
startService(new Intent(MainActivity.this, MyService.class));
}
});
bt3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 停止服务
stopService(new Intent(MainActivity.this, MyService.class));
}
});
bt4 = (Button) findViewById(R.id.bt4);
bt5 = (Button) findViewById(R.id.bt5);
bt4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
bindService(new Intent(MainActivity.this, MyService.class),
connection, BIND_AUTO_CREATE);
}
});
bt5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
unbindService(connection);
}
});
bt6 = (Button) findViewById(R.id.bt6);
bt6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startService(new Intent(MainActivity.this, MyIntentService.class));
}
});
}
}
/*
* @Title: MyIntentService.java
* @Description: TODO
* @author: 张志安
* @date: 2016-8-18 下午5:32:42
*
*/
package com.example.dyhdm_09_00androidthreadtest;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
/**
* TODO IntentService 异步的、会自动停止的服务
* @author 张志安
* @date: 2016-8-18 下午5:32:42
*/
public class MyIntentService extends IntentService {
/**
* <默认构造函数>
*/
public MyIntentService() {
super("MyIntentService");
}
/**
* 重载方法
*/
@Override
protected void onHandleIntent(Intent intent) {
Log.e("zza", Thread.currentThread().getId()+"");
}
/**
* 重载方法
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.e("zza", "onDestroy");
}
}
/*
* @Title: MyService.java
* @Description: TODO
* @author: 张志安
* @date: 2016-8-18 下午4:33:53
*
*/
package com.example.dyhdm_09_00androidthreadtest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* TODO 服务
*
* @author 张志安
* @date: 2016-8-18 下午4:33:53
*/
public class MyService extends Service {
private DownloadBinder mBind = new DownloadBinder();
class DownloadBinder extends Binder {
public void startDown() {
Log.e("zza", "startDown");
}
public void getProgress() {
Log.e("zza", "getProgress");
}
}
/**
* 重载方法
*/
@Override
public IBinder onBind(Intent intent) {
return mBind;
}
/**
* 重载方法 服务创建时调用
*/
@Override
public void onCreate() {
super.onCreate();
// 处理耗时逻辑
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// //具体处理逻辑
// }
// });
Log.e("zza", "onCreate");
Toast.makeText(this, "123", Toast.LENGTH_SHORT).show();
// 创建一个Notification对象,存储通知所需要的各种信息
Notification notification = new Notification(R.drawable.ic_launcher,
"hello zza", System.currentTimeMillis());
// 构建一个PendingIntentc传入setLatestEventInfo()的第四个参数,可以传null
Intent intent = new Intent(MyService.this, MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(MyService.this, 0, intent,
0);
// 对通知的布局进行设定
notification.setLatestEventInfo(MyService.this, "Zza", "Hello", pi);
startForeground(1, notification);
}
/**
* 重载方法 每次服务启动时调用
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("zza", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
/**
* 重载方法 服务销毁时调用
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.e("zza", "onDestroy");
// 处理耗时逻辑
// new Thread(new Runnable() {
//
// @Override
// public void run() {
// //具体处理逻辑
// stopSelf();
// }
// });
}
}
2.DYHDM_09_01ServiceBestPractice
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dyhdm_09_01servicebestpractice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.dyhdm_09_01servicebestpractice.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
<service android:name=".LongRunningService">service>
<receiver android:name=".AlarmReceiver">receiver>
application>
manifest>
/*
* @Title: AlarmReceiver.java
* @Description: TODO
* @author: 张志安
* @date: 2016-8-18 下午5:56:33
*
*/
package com.example.dyhdm_09_01servicebestpractice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* TODO 定时任务的广播接收者
* @author 张志安
* @date: 2016-8-18 下午5:56:33
*/
public class AlarmReceiver extends BroadcastReceiver {
/**
* 重载方法
*/
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context,LongRunningService.class));
}
}
/*
* @Title: LongRunningService.java
* @Description: TODO
* @author: 张志安
* @date: 2016-8-18 下午5:49:16
*
*/
package com.example.dyhdm_09_01servicebestpractice;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
/**
* TODO 设定一个定时任务
* @author 张志安
* @date: 2016-8-18 下午5:49:16
*/
public class LongRunningService extends Service {
/**
* 重载方法
*/
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 重载方法
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
Log.e("zza", "----"+new Date().toString());
}
}).start();
AlarmManager manage = (AlarmManager) getSystemService(ALARM_SERVICE);
int anMinute = 10*1000;
long triggerAtTime = SystemClock.elapsedRealtime()+anMinute;
Intent i = new Intent(LongRunningService.this,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);
manage.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
return super.onStartCommand(intent, flags, startId);
}
}
package com.example.dyhdm_09_01servicebestpractice;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this,LongRunningService.class));
}
}
代码下载地址