尝试通过服务发出通知

时间:2013-11-15 21:34:42

标签: java android

我目前正在尝试通过

让活动向服务发送意图
startService(Intent i)

但每当我运行它时都无效。我相信这是因为服务用于接收startService的方法不正确,但我不知道用什么代替它。这是活动:

package com.example.trackr;

import android.os.Bundle;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class StartScreen extends Activity {

    Intent startMonitor;
    Button newBut;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start_screen);
        startMonitor=new Intent();
        startMonitor.setClassName("com.example.trackr","StartService");
        startMonitor.putExtra("superAwesomeExtra", "FirstExtra");

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.start_screen, menu);
        return true;
    }

    public void callService(View view){
        startService(startMonitor);
        finish();
    }
}

这就是服务:

package com.example.trackr;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class StartService extends IntentService{

    public StartService(String name) {
        super(name);
    }

    public int onStartCommand(Intent in, int i, int k){
        NotificationCompat.Builder notBuild= new NotificationCompat.Builder(this);
        notBuild.setSmallIcon(R.drawable.secret_icon);
        notBuild.setContentText("Now in Secret Mode");
        notBuild.setContentTitle("Secret Mode");
        int notBuildIdentifier=001;

        Intent stopIntent=new Intent(this,CloseScreen.class);
        PendingIntent toStop=
            PendingIntent.getActivity(this,0,stopIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        notBuild.setContentIntent(toStop);

        NotificationManager notMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notMan.notify(notBuildIdentifier,notBuild.build());

            return 1;
    }

    @Override
    protected void onHandleIntent(Intent arg0) {

    }
}

我知道调用StartScreen中的callService是因为活动正在关闭,我只是不确定为什么没有创建通知。感谢您提供的所有帮助!

1 个答案:

答案 0 :(得分:0)

你的两个活动都在同一个包中,所以你可以做到

startMonitor = new Intent(this, StartService.class);

而不是空白的Intent,然后设置类名。

之前我没有使用过IntentService,但是根据文档的外观,您不应该使用onStartCommand作为代码的位置。 http://developer.android.com/reference/android/app/IntentService.html

看起来你应该实现onHandleIntent并在那里进行处理。

你可以改变它并设置一个断点来查看是否正在调用onHandleIntent吗?