如果没有按钮,请单击如何在android studio中的MainActivity中调用MyService类

时间:2016-02-25 12:44:42

标签: java android

不使用Button单击如何在MainActivity中调用MyService类。我的问题是在MainActivity类中调用MyService类,因为当应用程序启动通知自动启动时。

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyService my = new MyService();
    }
}

MyService.Java

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        showNotification();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
    private void showNotification() {
        NotificationCompat.Builder mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_loc)
                        .setContentTitle("Welcome to Brillio")
                        .setContentText("Hello Mansur, Welcome to Brillio! You'll be shortly attended by Renji! ")
                        .setPriority(2)
                        .setOnlyAlertOnce(false);
        Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        mBuilder.setSound(alarmSound);

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(2001, mBuilder.build());
    }
}

2 个答案:

答案 0 :(得分:1)

在没有任何用户互动的情况下,您可以开始服务,例如当您的活动开启时,您可以启动服务意图

 @Override
public void onResume() {
    super.onResume();
   startService(new Intent(this, MyService.class));
}

答案 1 :(得分:0)

将此添加到onCreate()方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startService(new Intent(this, MyService.class));
}