Android commonly used PM commands to start Service and Broadcast

I often PM commands during development, but I always can’t remember
them. Here are some verified commands, and they will be added continuously...

AMStart Service

Format
am start-foreground-service -n {package name}/{package name}.{Service name}

// 不带数据
am start-foreground-service -n com.testsdk/.MainEntrance

// 有数据,接收方法:intent.getDataString();
am start-foreground-service -n com.testsdk/.MainEntrance -d 123

// 有数据,接收方法:intent.getStringExtra("index");
am start-foreground-service -n com.testsdk/.MainEntrance -e index hello

// 多数据,接收方法:
// intent.getStringExtra("index1");
// intent.getIntExtra("index2", -1);
am start-foreground-service -n com.testsdk/.MainEntrance --es index1 Str --ei index2 1234

For higher versions of Android, when starting Service, using startservice will prompt "app is in background uid null", so it needs to be replaced with start-foreground-service.

Other content is being updated continuously. .

During the test, I found that the Service always destroyed after a few seconds because there was no front-end service set up. Modify it as follows (reprinted content):

private static final String ID = "channel_1";
private static final String NAME = "前台服务";
private void setForeground() {
    
    
	NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	NotificationChannel channel = new NotificationChannel(ID, NAME, NotificationManager.IMPORTANCE_HIGH);
	manager.createNotificationChannel(channel);
	Notification notification = new Notification.Builder(this, ID)
                .setContentTitle("收到一条重要通知")
                .setContentText("这是重要通知")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .build();
	startForeground(1, notification);
}

@Override
public void onCreate() {
    
    
	super.onCreate();
	setForeground();
}

Guess you like

Origin blog.csdn.net/cshoney/article/details/119949493