Подтвердить что ты не робот

Как начать работу, когда пользователь нажимает уведомление?

Я пытаюсь преобразовать некоторый код, который я нашел в учебнике для моего собственного использования. Первоначально код запускал список системных контактов, когда пользователь нажимал уведомление, созданное моим приложением. Я пытаюсь запустить Activity самостоятельно, а не запускать список контактов, но он не работает. В частности, ничего не происходит. Ошибка отсутствует, и мой Activity тоже не загружается. Окно уведомлений исчезает после нажатия, и исходный Activity все еще отображается.

Вот мой код:

public class MyBroadcastReceiver extends BroadcastReceiver {
    private NotificationManager mNotificationManager;
    private int SIMPLE_NOTFICATION_ID;

    public void onReceive(Context context, Intent intent){
        Bundle extras = intent.getExtras();

        String deal = (String) extras.get("Deal");
        String title = "Deal found at " + (String) extras.get("LocationName");

        mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notifyDetails = new Notification(R.drawable.icon, title,System.currentTimeMillis());

        Class ourClass;
        try {
            ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget");
            Intent startMyActivity = new Intent(context, ourClass);

            PendingIntent myIntent = PendingIntent.getActivity(context, 0,startMyActivity, 0);
            notifyDetails.setLatestEventInfo(context, title, deal, myIntent);
            notifyDetails.flags |= Notification.FLAG_AUTO_CANCEL;
            notifyDetails.flags |= Notification.DEFAULT_SOUND;
            mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Это моя запись в файле AndroidManifext.xml...

  <activity android:name=".ViewTarget" android:label="@string/app_name" >
        <intent-filter>
            <action android:name="com.kjdv.gpsVegas.ViewTarget" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
   </activity>

И это мой Activity, который я хочу запустить...

public class ViewTarget extends ListActivity {
    public ListAdapter getListAdapter() {
        return super.getListAdapter();
    }

    public ListView getListView() {
        return super.getListView();
    }

    public void setListAdapter(ListAdapter adapter) {
        super.setListAdapter(adapter);
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.locations);
        Log.v("db", "Inside ViewTarget");
    }
}
4b9b3361

Ответ 1

Я понял проблему. Я забыл включить имя пакета в объявление активности в файле манифеста.

Неправильно:

activity android:name=".ViewTarget" android:label="@string/app_name" 

Правильно:

activity android:name="com.kjdv.gpsVegas.ViewTarget" android:label="@string/app_name" 

Ответ 2

В какой версии Android вы работаете? Вместо этого вы можете попробовать использовать NotificationCompat. Этот класс включен в последний пакет поддержки.

Intent notificationIntent = new Intent(context, ViewTarget.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
                0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = context.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(contentIntent)
       .setSmallIcon(R.drawable.app_icon)
       .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.app_icon))
       .setTicker(payload)
       .setWhen(System.currentTimeMillis())
       .setAutoCancel(true)
       .setContentTitle("Message")
       .setContentText(payload);
Notification n = builder.getNotification();

n.defaults |= Notification.DEFAULT_ALL;
nm.notify(0, n);

EDIT: Я знаю, что это старый вопрос/вопрос, но этот ответ помог мне показать активность при нажатии уведомления. Для тех людей, что это не работает, вероятно, потому, что вы не "зарегистрировали" свою деятельность в своем манифесте. Например:

<activity
   android:name="com.package.name.NameOfActivityToLaunch"
   android:label="Title of Activity" >
   <intent-filter>
     <action android:name="com.package.name.NAMEOFACTIVITYTOLAUNCH" />

     <category android:name="android.intent.category.DEFAULT" />
   </intent-filter>
</activity>

И, надеюсь, это должно сработать. Надеюсь, это помогло...

Ответ 3

вы должны установить действие и категорию для намерения.

Intent startMyActivity = new Intent(context, ourClass);
startMyActivity .setAction(Intent.ACTION_MAIN);
startMyActivity .addCategory(Intent.CATEGORY_LAUNCHER);

работает

Ответ 4

Можете ли вы попробовать удалить фильтр Intent, чтобы он выглядел так:

<activity android:name=".ViewTarget" android:label="@string/app_name" />

Кроме того, не уверен, что этот код будет работать:

ourClass = Class.forName("com.kjdv.gpsVegas.ViewTarget"); Intent startMyActivity = new Intent(context, ourClass);

Можете ли вы попробовать это следующим образом:

Intent startMyActivity = new Intent(context, ViewTarget.class);

Ответ 5

проверить этот код

            public class TestActivity extends Activity {
private static final int UNIQUE_ID = 882;

public static NotificationManager nm;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        Intent navigationIntent = new Intent();


    navigationIntent.setClass(classname.this, MainActivity.class);


    PendingIntent pi = PendingIntent.getActivity(this, 0, navigationIntent,
            0);

    String body = "New notificattion added!!!";
    String title = "Notification";


    Notification n = new Notification(R.drawable.icon, body,
            System.currentTimeMillis());

            //this is for giving number on the notification icon

    n.number = Integer.parseInt(responseText);

    n.setLatestEventInfo(this, title, body, pi);
    n.defaults = Notification.DEFAULT_ALL;

    nm.notify(UNIQUE_ID, n);

Ответ 6

Чтобы запустить Activity с Intent, вам нужно добавить флаг:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Это верно, даже если вы объявляете класс в конструкторе Intent.