这就是我为服务所拥有的:(确保您在 onReceive 中使用正确的意图。onReceive 接收一个意图;启动服务的那个。我注意到当 Eclipse 创建 onReceive 时,Intent 参数的默认名称是“intent “(你不想使用这个)。另外,你为什么使用变量上下文而不是关键字 this?Service 类扩展了 ContextWrapper,它扩展了 Context。
package com.example.solution;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class Serv extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
String message = "Hello";
long when = System.currentTimeMillis();
String notificationText = "Message From SimplePay";
//get the notification service
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, notificationText,when);
String title = this.getString(R.string.app_name);
String messageBody = "You have " + 1 + " payment request pending";
Intent notificationIntent = new Intent(this,InvoiceActivity.class);
notificationIntent.putExtra("invoice",message);
//always create a new activity! So recent values get updated
PendingIntent intentp = PendingIntent.getActivity(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
notification.setLatestEventInfo(this,title,messageBody,intentp);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0,notification);
return START_STICKY;
}
}
这是主要活动(启动器)。
package com.example.solution;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
startService(new Intent(this,Serv.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
stopService(new Intent(this,Serv.class));
}
}
这是InvoiceActivity
package com.example.solution;
import android.app.Activity;
import android.util.Log;
public class InvoiceActivity extends Activity {
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Log.e("MESSAGE",getIntent().getExtras().getString("invoice"));
}
}
希望这可以帮助