在我的应用程序中我使用IntentService发送短信.
@Override
protected void onHandleIntent(Intent intent) {
Bundle data = intent.getExtras();
String[] recipients = null;
String message = getString(R.string.unknown_event);
String name = getString(R.string.app_name);
if (data != null && data.containsKey(Constants.Services.RECIPIENTS)) {
recipients = data.getStringArray(Constants.Services.RECIPIENTS);
name = data.getString(Constants.Services.NAME);
message = data.getString(Constants.Services.MESSAGE);
for (int i = 0; i < recipients.length; i++) {
if(!StringUtils.isNullOrEmpty(recipients[i])) {
try {
Intent sendIntent = new Intent(this, SMSReceiver.class);
sendIntent.setAction(Constants.SMS.SEND_ACTION);
PendingIntent sendPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, sendIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent deliveryIntent = new Intent(this, SMSReceiver.class);
deliveryIntent.setAction(Constants.SMS.DELIVERED_ACTION);
PendingIntent deliveryPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, deliveryIntent, …Run Code Online (Sandbox Code Playgroud) 此代码应该使用服务来显示Toast消息.没有错误,但它没有显示祝酒词.
主要活动
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i= new Intent(this, BackgroundMusic.class);
this.startService(i);
}
}
Run Code Online (Sandbox Code Playgroud)
服务(它被称为背景音乐,但现在它应该显示一个祝酒词)
public class BackgroundMusic extends IntentService {
public BackgroundMusic() {
super("BackgroundMusic");
}
@Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = …Run Code Online (Sandbox Code Playgroud) 我正在尝试让我的IntentService显示Toast消息,但是当从onHandleIntent消息发送它时,toast显示但是卡住了屏幕并且从不离开.我猜它是因为onHandleIntent方法不会发生在主服务线程上,但是我怎么能移动呢?
有人有这个问题并解决了吗?
更新: 我不同意这是一个重复 - 因为我正在寻找一种方法退出主应用程序,仍然显示从服务Toast.
在一个非常简单的测试应用程序中我有2个按钮:

单击任何按钮将运行带有相应操作字符串的服务("打开"或"闪烁") -
public class OpenActivity extends Activity {
private Intent mServiceIntent;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open);
mServiceIntent = new Intent(this, RegionService.class);
}
public void openCar(View v) {
mServiceIntent.setAction("open");
startService(mServiceIntent);
}
Run Code Online (Sandbox Code Playgroud)
public class RegionService extends IntentService {
private static final String TAG = "RegionService";
@Override
protected void onHandleIntent(Intent intent) {
Log.d(TAG, "Received an intent: " + intent);
String action = intent.getAction();
Log.d(TAG, "Received an action: " + …Run Code Online (Sandbox Code Playgroud)