avatar

Android后台服务

Android后台服务

随着Android版本不断更新,后台服务是越来越难存活了.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// MainActivity.java
public class MainActivity extends AppCompatActivity {
private IncomingMessageHandler mHandler;
/**
* {@link Handler}允许您发送与线程相关联的消息。
* 它也用于使开始和停止视图在短时间内闪烁。
*/
private class IncomingMessageHandler extends Handler {
// 使用弱引用防止内存泄露
private WeakReference<MainActivity> mActivity;
IncomingMessageHandler(MainActivity activity) {
super(/* default looper */);
this.mActivity = new WeakReference<>(activity);
}
@Override
public void handleMessage(Message msg) {
MainActivity mSchedulerAcitvity = mActivity.get();
if (mSchedulerAcitvity == null) {
return;
}
switch (msg.what) {
case 0:
// msg.obj
break;
}
}
}
@Override
protected void onStart() {
super.onStart();
// 启动服务并提供一种与此类通信的方法。
mHandler = new IncomingMessageHandler(this);
Intent startServiceIntent = new Intent(this, BTService.class);
Messenger messengerIncoming = new Messenger(mHandler);
startServiceIntent.putExtra(MESSENGER_INTENT_KEY, messengerIncoming);
startService(startServiceIntent);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// BTService.java
public class BTService extends Service {
public static final String MESSENGER_INTENT_KEY = "MESSENGER_INTENT_KEY";
private Messenger mActivityMessenger;
private Handler handler;
private void sendMessage(int messageID, Object params) {
if (mActivityMessenger == null) {
return;
}
Message m = Message.obtain();
m.what = messageID;
m.obj = params;
try {
mActivityMessenger.send(m);
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void fe() {
String notifyId = "UA631";
Notification.Builder builder = new Notification.Builder(this);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel mChannel = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mChannel = new NotificationChannel(notifyId, notifyId, NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(mChannel);
builder = new Notification.Builder(this, notifyId);
}
builder.setTicker("uploadservice");
builder.setContentText("请保持程序在后台运行");
builder.setWhen(System.currentTimeMillis());
Notification notification = builder.build();
startForeground(1, notification);
}
@Override
public void onDestroy() {
MyLog.d("onDestroy ===== ");
super.onDestroy();
Intent startServiceIntent = new Intent(this, BTService.class);
startServiceIntent.putExtra(MESSENGER_INTENT_KEY, mActivityMessenger);
startService(startServiceIntent);
stopForeground(true);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("HandlerLeak")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
mActivityMessenger = intent.getParcelableExtra(MESSENGER_INTENT_KEY);
}
MyLog.d("onStartCommand ===== ");
fe();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 0x10000) {
handler.sendEmptyMessageDelayed(0x10000, 40000);
}
}
};
handler.sendEmptyMessageDelayed(0x10000, 40000);
return START_STICKY;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!-- AndroidManifest.xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.uascent.ua631">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/logo"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".page.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".service.BTService" />
</application>
</manifest>
文章作者: pengweifu
文章链接: https://www.pengwf.com/2019/10/23/android/ANDROID-BackService/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 麦子的博客
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论