I have a MainActivity
class which has a NotificationsListener
(seperate class). When a notification appears, it calls my gethtml
class. They both extend Activity
but the startActivity
in my gethtml
class doesn't work... (If I copy and test this code in my MainActivity
, it works fine)... Anyone have an idea why it isn't working?
This is the main class:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_EXAMPLE");
startService(new Intent(MainActivity.this, NLService.class));
Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
This is the notification listener:
public class NLService extends NotificationListenerService {
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.kpbird.nlsexample.NOTIFICATION_LISTENER_SERVICE_EXAMPLE");
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onNotificationPosted(StatusBarNotification sbn) {
new Thread(new Runnable() {
public void run(){
Looper.prepare();
int cangethtml = 1;
try{
if(cangethtml==1){
cangethtml = 0; //only runs once
new html();
}
}finally{Looper.loop();}
};
}).start();
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn) {}
}
This is the final class which doesn't open the website through the startActivity
:
public class html extends Activity{
public html() {
try {
Intent i2 = new Intent("android.intent.action.MAIN");
i2.setComponent(ComponentName.unflattenFromString("com.android.chrome/com.android.chrome.Main"));
i2.addCategory("android.intent.category.LAUNCHER");
i2.setData(Uri.parse("https://wwww.google.com"));
startActivity(i2);
} finally{}
}
}
You need the context of the Activity. startActivity
will be called in the context of Activity
.
With reference to the developer's forum:
You should write
Context.startActivity(i2);
instead of
startActivity(i2);
Plus, make sure you don't forget to have a corresponding <activity>
declaration in your package's AndroidManifest.xml
.
For instance: Check in AndroidManifest.xml
for all the classes defined by you. You have:
<activity android:name="packageName.className"/>
If your html
class is not defined in AndroidManifest.xml
, you can not access the methods and layouts defined in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.