安卓服务常驻

最近研究怎样防止服务被杀死,网上百度了下,发现基本就两只设置方法,1.在Service onStartCommand中返回super.onStartCommand(intent, START_STICKY, startId);,这样进程被一键杀死后会立即自动重启。  2.注册receiver,监听开机等事件,在onReceive中启动服务。   

在模拟器上没问题,可以正常启动,而且杀不死,但在手机上一直没法启动,后来发现是小米系统设置的问题,在安全中心中允许自动启动就行了,默认已经允许微信,qq自动启动,所以微信qq杀不死。

注意:新安装的应用要启动一次后注册的receiver才能生效,以后不管是应用被杀死,还是刚开机,都能收到解锁等广播了


附上代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.kaijiqidong"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <!-- 监听开机启动权限 -->
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".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>
        
         <receiver android:name="com.example.kaijiqidong.MyReceiver">
            <intent-filter>
                <!-- 应用卸载 -->
                <action android:name="android.intent.action.PACKAGE_REMOVED"/>
                <data android:scheme="package"/>
            </intent-filter>
            <intent-filter>
                <!-- 开机 -->
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <!-- 解锁 -->
                <action android:name="android.intent.action.USER_PRESENT" />
            </intent-filter>
        </receiver>
        
         <service android:name="com.example.kaijiqidong.MyService" ></service>
    </application>

</manifest>


MainActivity里面的代码可以忽略。。。

package com.example.kaijiqidong;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		findViewById(R.id.but).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startService(new Intent(getApplicationContext(), MyService.class));
				
				bindService(new Intent(getApplicationContext(), MyService.class), new ServiceConnection() {
					
					@Override
					public void onServiceDisconnected(ComponentName name) {
						// TODO Auto-generated method stub
						
					}
					
					@Override
					public void onServiceConnected(ComponentName name, IBinder service) {
						// TODO Auto-generated method stub
						
					}
				}, BIND_AUTO_CREATE);
			}
		});
	}
}



package com.example.kaijiqidong;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		System.out.println("收到  ---- "+intent.getAction());
		//启动服务
		context.startService(new Intent(context, MyService.class));
		
		Toast.makeText(context, "fu wu  qi  dong", 0).show();
	}

}


package com.example.kaijiqidong;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service{

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		//返回super.onStartCommand(intent, START_STICKY, startId);
		//保证被一键清理后自动重启服务
		return super.onStartCommand(intent, START_STICKY, startId);
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Intent intent=new Intent(getApplicationContext(), MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}

}




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在 Android 11 中,要让服务常驻内存,可以通过使用前台服务(Foreground Service)实现。前台服务是一种特殊的服务类型,可以将服务标记为正在运行的重要服务,以便系统知道它们需要更多的资源(例如内存),从而更不可能被系统杀死。 要创建前台服务,您需要在服务的 onStartCommand() 方法中调用 startForeground() 方法,并传递一个 Notification 对象。该 Notification 对象将显示在系统状态栏中,并告知用户该服务正在运行。如果您需要更新通知内容,可以调用 NotificationManager 的 startForeground() 方法,传递一个更新后的 Notification 对象。 需要注意的是,在前台服务不再需要时,应该及时调用 stopForeground() 方法,以便将服务降为后台服务,释放资源。 下面是一个前台服务的示例代码: ``` public class MyForegroundService extends Service { private static final int NOTIFICATION_ID = 1; @Override public int onStartCommand(Intent intent, int flags, int startId) { Notification notification = createNotification(); startForeground(NOTIFICATION_ID, notification); // do some work here return START_STICKY; } private Notification createNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("My Foreground Service") .setContentText("Service is running...") .setSmallIcon(R.drawable.ic_notification); return builder.build(); } @Override public void onDestroy() { super.onDestroy(); stopForeground(true); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } } ``` 在此示例中,创建了一个名为 MyForegroundService 的前台服务。在 onStartCommand() 方法中调用了 startForeground() 方法,并传递了一个 Notification 对象,该对象显示了服务正在运行的信息。在 onDestroy() 方法中,调用了 stopForeground() 方法,以便将服务降为后台服务

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值