启动前台服务 android,android - android使用START_STICKY启动前台服务 - 堆栈内存溢出...

ublic class MyActivity2 extends Activity {

private Intent serviceIntent;

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

serviceIntent = new Intent(this, MyService.class);

serviceIntent.putExtra("name", "ahmet vefa saruhan");

startService(serviceIntent);

findViewById(R.id.textview).setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

stopService(new Intent(getApplicationContext(),MyService.class));

}

});

}

}

public class MyService extends Service {

private String myaction;

@Nullable

@Override

public IBinder onBind(Intent intent) {

return null;

}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {

Log.d("MYSERVICE STATUS: "," ONSTARTCOMMAND action : " + ((intent != null && intent.getStringExtra("name") != null) ? intent.getStringExtra("name") : "yok") + " OLD ACTION : "+(myaction != null ? myaction : "yok"));

Log.d("MYTHREAD name : ",Thread.currentThread().getName());

//intent.putExtra("name","isim değişti");

myaction = (intent != null) ? intent.getAction() : null;

return START_STICKY;

}

@Override

public void onCreate() {

super.onCreate();

Log.d("MYSERVICE STATUS: "," ONCREATED");

}

@RequiresApi(api = Build.VERSION_CODES.O)

private void startMyOwnForeground()

{

String NOTIFICATION_CHANNEL_ID = "example.permanence";

String channelName = "Background Service";

NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);

chan.setLightColor(Color.BLUE);

chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

assert manager != null;

manager.createNotificationChannel(chan);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

Notification notification = notificationBuilder.setOngoing(true)

.setContentTitle("App is running in background")

.setPriority(NotificationManager.IMPORTANCE_MIN)

.setCategory(Notification.CATEGORY_SERVICE)

.build();

startForeground(2, notification);

}

@Override

public void onDestroy() {

Log.d("MYSERVICE STATUS: "," ONDESTROYED");

super.onDestroy();

}

@Override

public void onTaskRemoved(Intent rootIntent) {

Log.d("MYSERVICE STATUS: "," onTaskRemoved");

super.onTaskRemoved(rootIntent);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值