2017-01-18 7 views
0

У меня есть приложение для Android, и я запускаю свое приложение с помощью MyApp.java, где я объявляю все, и это моя отправная точка приложения. В onCreate(), я начинаю услугу с намерением.AlertDialog от службы в любой части приложения

Я также создать экземпляр службы и попытаться получить доступ к объекту службы внутри таймера обратного отсчета onFinish(), как -

MYService myService = new MYService(); 
myService.getDialog(); 

И в MYSERVICE, у меня есть этот метод как -

public void showMsg(){ 
     AlertDialog alertDialog = new AlertDialog.Builder(getApplication()) 
       .setTitle("Success!") 
       .setMessage("Countdown") 
       .setPositiveButton("Success", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
        } 
       }).create(); 

     alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); 
     alertDialog.show(); 
    } 

Моя цель какая бы ни была часть приложения, в котором я находилась, как в отношении активности или фрагмента, я должен быть в состоянии получить этот alertdialog через 5 секунд таймера обратного отсчета. Как это достичь?

ответ

0

Вы можете использовать BoundService:

  1. Создать основной вид деятельности, что любая активность в вашем приложении расширения основной деятельности.
  2. Привяжите это основное действие для обслуживания, которое вы создали.
  3. Когда истечет время или истекает срок действия таймера, отправьте сообщение в основное действие.
  4. Когда действие получает сообщение, оно отобразит ваше диалоговое окно.

Здесь вы можете обратиться сюда example.

Для получения более подробной информации отметьте here.

Спасибо.

0

В манифесте

<application 
android:allowBackup="true" 
android:icon="@mipmap/ic_launcher" 
android:label="@string/app_name" 
android:supportsRtl="true" 
android:theme="@style/AppTheme"> 
<activity android:name=".MainActivity"> 
    <intent-filter> 
     <action android:name="android.intent.action.MAIN" /> 

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

<service 
    android:name=".ShowAlertService" 
    android:label="@string/app_name"/> 

В вашем MainActivity.JAVA

import android.app.AlertDialog; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.support.v4.content.LocalBroadcastManager; 
import android.support.v7.app.AppCompatActivity; 

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Intent intent = new Intent(getApplicationContext(),ShowAlertService.class); 
     startService(intent); 

    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     // This registers mMessageReceiver to receive messages. 
     LocalBroadcastManager.getInstance(this) 
       .registerReceiver(mMessageReceiver, 
         new IntentFilter("broadcastMsg")); 
    } 

    // Handling the received Intents for the "my-integer" event 
    private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 

        if(intent.getBooleanExtra("showalert",false)) 
        { 
         showMsg(); 
        } 


     } 
    }; 

    @Override 
    protected void onPause() { 
     // Unregister since the activity is not visible 
     LocalBroadcastManager.getInstance(this) 
       .unregisterReceiver(mMessageReceiver); 
     super.onPause(); 
    } 


    public void showMsg(){ 
     AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this) 
       .setTitle("Success!") 
       .setMessage("Countdown") 
       .setPositiveButton("Success", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 

        } 
       }).create(); 
     alertDialog.show(); 
    } 

} 

и наконец ваш класс обслуживания будет как

import android.app.Service; 
import android.content.Intent; 
import android.os.Handler; 
import android.os.IBinder; 
import android.support.v4.content.LocalBroadcastManager; 
import android.util.Log; 

import java.util.Timer; 
import java.util.TimerTask; 

public class ShowAlertService extends Service { 

    Timer timer; 
    TimerTask timerTask; 
    String TAG = "Timers"; 
    int Your_X_SECS = 5; 


    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     Log.e(TAG, "onStartCommand"); 
     super.onStartCommand(intent, flags, startId); 

     startTimer(); 

     return START_STICKY; 
    } 


    @Override 
    public void onCreate() { 
     Log.e(TAG, "onCreate"); 


    } 

    @Override 
    public void onDestroy() { 
     Log.e(TAG, "onDestroy"); 
     stoptimertask(); 
     super.onDestroy(); 


    } 

    //we are going to use a handler to be able to run in our TimerTask 
    final Handler handler = new Handler(); 


    public void startTimer() { 
     //set a new Timer 
     timer = new Timer(); 

     //initialize the TimerTask's job 
     initializeTimerTask(); 

     //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms 
     timer.schedule(timerTask, 5000, Your_X_SECS * 1000); // 
     //timer.schedule(timerTask, 5000,1000); // 
    } 

    public void stoptimertask() { 
     //stop the timer, if it's not already null 
     if (timer != null) { 
      timer.cancel(); 
      timer = null; 
     } 
    } 

    public void initializeTimerTask() { 

     timerTask = new TimerTask() { 
      public void run() { 

       //use a handler to run a toast that shows the current timestamp 
       handler.post(new Runnable() { 
        public void run() { 

          sendMessage(); 

        } 
       }); 
      } 
     }; 
    } 

    //Send message to activity 
    private void sendMessage() { 
     Intent intent = new Intent("broadcastMsg"); 
     intent.putExtra("showalert",true); 
     LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
    } 

} 

Отправить Broadcast сообщение «showalert» для активности и отображения предупреждения, как только вы получите широковещательное сообщение.

+0

Вы не можете отобразить диалог из службы. –

+0

@RajenRaiyarela Посмотрите на этот фрагмент из класса сервиса 'AlertDialog alertDialog = new AlertDialog.Builder (MainActivity.activity)' –

+0

Я беру этот экземпляр и проверяю статическое значение, является ли оно нулевым или нет. Он не подходит к передовой практике, но он работает. –

 Смежные вопросы

  • Нет связанных вопросов^_^