从Android服务创建意向选择器

时间:2012-09-30 09:57:26

标签: android android-intent android-service

我有一个GCM服务,我想创建一个Intent选择器(Intent.createChooser()),但尽管我一直在尝试各种各样的事情,但我总是得到Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?我做错了什么或者你是不是只是不是从服务中做到这一点?

服务的代码如下(我尝试过各种各样的评论);

public class GCMIntentService extends GCMBaseIntentService 
{
    // ...

    protected void onMessage(Context context, Intent intent)
    {
        Log.i(TAG, "Received message");
        String message = "Push received";
        displayMessage(context, message);
        fireIntent(context, message);
    }

    private void fireIntent(Context context, String url)
    {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, url);
        //intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(Intent.createChooser(intent, "Share URL"));
        //context.startActivity(Intent.createChooser(intent, "Share URL"));
        //sendBroadcast(intent);
    }
}

提前致谢。

1 个答案:

答案 0 :(得分:1)

确实,从Activity开始Service不是一个好主意,因为Service在后​​台运行,而其他一些应用程序可能在前台。在其他应用程序运行时弹出Intent选择器将完全破坏用户体验。一个好的决定是使用可点击的Notifications让用户在需要时自己启动Activity。希望这可以帮助。