【问题标题】:How can I trigger my notification from a method?如何从方法触发我的通知?
【发布时间】:2015-08-14 07:40:44
【问题描述】:

我正在尝试触发我的通知底部。我按照这个示例代码 http://www.compiletimeerror.com/2013/10/status-bar-notification-example-in.html#.VWtoS1xViko

当我从应用程序的主要活动 HomeActivity 调用方法时,我可以触发通知。当尝试从应用程序中的一种方法调用时,没有任何反应。 (例如)

HomeActivity homeactivity = new HomeActivity();
homeactivity.Notify("Title: ...", "Msg: ... ");

这里是事件的日志。我在按下 5 次按钮后触发警报

05-31 18:33:41.533  10118-10118/com.myapp.md E/>>>>>>﹕ MultiClickEvent clickCount = 5
05-31 18:33:41.543  10118-10118/com.myapp.md E/>>>>>>>﹕ in onActivation of HWReceiver
05-31 18:33:41.603  10118-10118/com.myapp.md V/Vibrator﹕ Called vibrate(long) API - PUID: 10588, PackageName: com.myapp.md
05-31 18:33:41.603  10118-10118/com.myapp.md V/Vibrator﹕ vibrate - PUID: 10588, PackageName: com.myapp.md, ms: 3000, mag: -1
05-31 18:33:41.643  10118-10118/com.myapp.md D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4
05-31 18:33:41.643  10118-10118/com.myapp.md D/AbsListView﹕ unregisterIRListener() is called
05-31 18:33:41.643  10118-10118/com.myapp.md D/AbsListView﹕ onVisibilityChanged() is called, visibility : 4
05-31 18:33:41.643  10118-10118/com.myapp.md D/AbsListView﹕ unregisterIRListener() is called
05-31 18:33:41.643  10118-11068/com.myapp.md E/>>>>>>﹕ in CurrentLocationProvider CONSTRUCTOR - trying to retrieve location from getLastKnownLocation()
05-31 18:33:41.833  10118-11068/com.myapp.md I/com.myapp.md.alert.SMSAdapter﹕ Sms sent: I need IMMEDIATE help! - I'm here https://maps.google.com/maps?q=40.7348922,-73.977548 via network
05-31 18:33:44.883  10118-10118/com.myapp.md E/>>>>>>>﹕ in onReceive of HWReceiver
05-31 18:33:44.883  10118-10118/com.myapp.md E/>>>>>>>﹕ in onReceive of HWReceiver context com.myapp.md.trigger.HardwareTriggerService@429b89b0
05-31 18:33:44.883  10118-10118/com.myapp.md E/>>>>>>>﹕ in onReceive of HWReceiver intent Intent { act=android.intent.action.SCREEN_ON flg=0x50000010 }

我尝试将通知放在我的 SMSAdapter 中

public class SMSAdapter {
    private static final String LOG_TAG = SMSAdapter.class.getName();

    public void sendSMS(Context context, String phoneNumber, String message) {
//        Log.e("20140411", "sending fake SMS -> " + message);
        if(!ApplicationSettings.isFirstMsgSent(context)){
            ApplicationSettings.setFirstMsgSent(context, true);
        }
        SmsManager smsManager = getSmsManager();
        try {
            smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            Log.i(LOG_TAG, "Sms sent: " + message);
            HomeActivity homeactivity = new HomeActivity();
            homeactivity.Notify("Title: Text SOS",
                    "Msg: Alerting your emergency contacts ");
        } catch (Exception exception) {
            Log.e(LOG_TAG, "Sending SMS failed " + exception.getMessage());
        }
    }

    SmsManager getSmsManager() {
        return SmsManager.getDefault();
    }
}

当我这样做时,我会收到此消息

05-31 18:39:33.163  18640-19982/com.textsosalert.md E/>>>>>>﹕ in CurrentLocationProvider CONSTRUCTOR - trying to retrieve location from getLastKnownLocation()
05-31 18:39:33.383  18640-19982/com.textsosalert.md I/com.textsosalert.md.alert.SMSAdapter﹕ Sms sent: I need IMMEDIATE help! - I'm here https://maps.google.com/maps?q=40.7348689,-73.9775756 via network
05-31 18:39:33.383  18640-19982/com.textsosalert.md E/com.textsosalert.md.alert.SMSAdapter﹕ Sending SMS failed Can't create handler inside thread that has not called Looper.prepare()

这是我定义的 Notify 方法:

@SuppressWarnings("deprecation")
public void Notify(String notificationTitle, String notificationMessage) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    @SuppressWarnings("deprecation")
    Notification notification = new Notification(R.drawable.icon_sos,
            "New Message", System.currentTimeMillis());

    Intent notificationIntent = new Intent(this, HomeActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
            notificationIntent, 0);

    notification.setLatestEventInfo(HomeActivity.this, notificationTitle,
            notificationMessage, pendingIntent);
    notificationManager.notify(9999, notification);
}

【问题讨论】:

    标签: android android-notifications android-handler android-looper


    【解决方案1】:

    问题是你打电话给new HomeActivity(),这是你不应该做的事情。 Android 中的 Activity 始终使用 startActivity()startActivityForResult() 启动,并且永远不应使用 new 显式创建。

    当您调用new HomeActivity() 时,不会调用任何 Activity 生命周期回调,因此 Activity 将没有有效的 Context。

    所以,这行不通:

    HomeActivity homeactivity = new HomeActivity();
    homeactivity.Notify("Title: ...", "Msg: ... ");
    

    如果您想拥有一个可以在代码中不同位置重复使用的方法,请将其放在单独的类中,并让该方法将 Context 作为参数。

    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    
    public class MyNotification {
    
        @SuppressWarnings("deprecation")
        public static void notify(Context context, String notificationTitle, String notificationMessage) {
            NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            @SuppressWarnings("deprecation")
            Notification notification = new Notification(R.drawable.icon_sos,
                    "New Message", System.currentTimeMillis());
    
            Intent notificationIntent = new Intent(context, HomeActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                    notificationIntent, 0);
    
            notification.setLatestEventInfo(context, notificationTitle,
                    notificationMessage, pendingIntent);
            notificationManager.notify(9999, notification);
        }
    }
    

    然后在 SMSAdapter 中,您将拥有:

        try {
            smsManager.sendTextMessage(phoneNumber, null, message, null, null);
            Log.i(LOG_TAG, "Sms sent: " + message);
            /* Don't do this:
            HomeActivity homeactivity = new HomeActivity();
            homeactivity.Notify("Title: Text SOS",
                    "Msg: Alerting your emergency contacts ");
            */
    
            //Do this instead:
            MyNotification.notify(context, "Title: Text SOS",
                    "Msg: Alerting your emergency contacts ");
    
        } catch (Exception exception) {
            Log.e(LOG_TAG, "Sending SMS failed " + exception.getMessage());
        }
    

    还请注意,您可以使用 this 作为 context 从 HomeActivity 调用它:

     MyNotification.notify(this, "Title: Text SOS",
                    "Msg: Alerting your emergency contacts ");
    

    【讨论】:

    • @JackShultz 太好了!请注意,如果您想从 HomeActivity 调用它,只需将 this 输入到 context 参数即可。
    • 很酷,很高兴了解 Activity 类以供将来参考。
    猜你喜欢
    • 2012-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2019-12-12
    • 2011-09-22
    相关资源
    最近更新 更多